<template>
  <div class="table-box">
    <div class="table-box-title" v-if="type == 'show'">表</div>
    <div v-else class="box">
      <div class="header">
        <div class="title">{{ showContent.table }}</div>
        <div class="btn" @click="handleEdit">
          <el-icon><Edit /></el-icon>
        </div>
        <div class="btn" @click="handleDelete">
          <el-icon color="red"><Delete /></el-icon>
        </div>
      </div>
      <div class="box-content">
        <div class="box-content-item">
          <div class="label">字段：</div>
          <div class="value">
            <el-tag v-for="(item, index) in showContent.fields" :key="index">{{ item.reName }}</el-tag>
          </div>
        </div>
        <div class="box-content-item">
          <div class="label">条件：</div>
          <div class="value">
            <el-tree
              empty-text="暂无条件"
              v-if="showContent.condition"
              :data="showContent.condition"
              :props="{ label: 'sql' }"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="表" width="80%" align-center append-to-body v-model="isShowDialog">
      <el-form :model="formData" label-width="80px" :rules="formRules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据源" prop="datasourceId">
              <el-select
                v-model="formData.datasourceId"
                placeholder="请选择数据源"
                filterable
                :disabled="tableStatus == 'edit' ? true : false"
                @change="dataSourceChange"
              >
                <el-option
                  style="height: 68px"
                  v-for="item in dataSourceList"
                  :key="item._id"
                  :label="item.datasourceName"
                  :value="item._id"
                >
                  <div style="font-size: 16px">{{ item.datasourceName }}</div>
                  <div style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                    {{ item.type }}
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表" prop="tableId">
              <el-select
                v-model="formData.tableId"
                placeholder="请选择表"
                filterable
                :disabled="tableStatus == 'edit' ? true : false"
                @change="tableChange"
              >
                <el-option v-for="item in tableList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重命名" prop="tableReName">
              <el-input
                :disabled="tableStatus == 'edit' ? true : false"
                v-model="formData.tableReName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字段">
              <el-table
                :data="fieldList"
                ref="tableRef"
                border
                max-height="50vh"
                style="width: 100%"
                row-key="COLUMN_NAME"
                @selection-change="tableSelect"
              >
                <el-table-column type="selection" align="center" width="55" />
                <el-table-column label="字段名" prop="COLUMN_NAME" align="center" />
                <el-table-column label="字段类型" prop="DATA_TYPE" align="center" width="100px" />
                <el-table-column label="字段长度" prop="DATA_LENGTH" align="center" width="100px" />
                <el-table-column label="注释" prop="COMMENTS" align="center">
                  <template #default="scope">
                    <span v-if="scope.row.FIELD_NAME">{{ scope.row.FIELD_NAME }}</span>
                    <span v-else>{{ scope.row.COMMENTS }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="标签" prop="RANGE" align="center">
                  <template #default="scope">
                    <div v-if="scope.row.RANGE">
                      <!-- {{ scope.row.RANGE_VALUE || scope.row.RANGE }} -->
                      {{ scope.row.RANGE }}
                    </div>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="重命名" prop="reName" align="center">
                  <template #default="scope">
                    <el-input v-model="scope.row.reName" placeholder="请输入重命名" />
                  </template>
                </el-table-column>
                <!-- <el-table-column label="操作" align="center" width="120px">
                  <template #default="scope">
                    <span v-if="scope.row.RANGE">
                      <el-tooltip placement="top" content="标签详情">
                        <el-icon style="margin-left: 10px; cursor: pointer" :size="20" color="#E6A23C">
                          <Search />
                        </el-icon>
                      </el-tooltip>
                      <el-tooltip v-if="!scope.row.tag" placement="top" content="启用标签">
                        <el-icon
                          style="margin-left: 10px; cursor: pointer"
                          :size="20"
                          color="#ccc"
                          @click="scope.row.tag = true"
                        >
                          <Flag />
                        </el-icon>
                      </el-tooltip>
                      <el-tooltip v-else placement="top" content="移除标签">
                        <el-icon
                          style="margin-left: 10px; cursor: pointer"
                          :size="20"
                          color="#67C23A"
                          @click="scope.row.tag = false"
                        >
                          <Flag />
                        </el-icon>
                      </el-tooltip>
                    </span>
                    <el-tooltip placement="top" content="自定义标签">
                      <el-icon style="margin-left: 10px; cursor: pointer" :size="20" color="#ccc">
                        <EditPen />
                      </el-icon>
                    </el-tooltip>
                  </template>
                </el-table-column> -->
              </el-table>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="筛选">
              <Condition ref="conditionRef" :fieldList="fieldList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="handelSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { findTableName, findColumnName } from '@/api/datasourceCenter'
import { Edit, Delete, Search, Flag, EditPen } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, reactive } from 'vue'
import Condition from './condition.vue'
import { getConditionTreeData } from '../index'
import { useAntvStore } from '@/store/modules/antvStore'
const antvStore = useAntvStore()
const getNode = inject('getNode')

const prop = defineProps({
  type: {
    type: String,
    default: 'default'
  }
})
const isShowDialog = ref(false)
const conditionRef = ref(null)
const tableRef = ref(null)
const dataSourceList = ref([])
const formData = reactive({
  datasourceId: '',
  tableId: '',
  tableReName: ''
})
const formRules = reactive({
  datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
  tableId: [{ required: true, message: '请选择表', trigger: 'change' }],
  tableReName: [{ required: true, message: '请输入重命名', trigger: 'blur' }]
})
const currentDb = ref({})
const tableList = ref([])
const fieldList = ref([])
const choosedFields = ref([])
const tableStatus = ref('add')
const showContent = reactive({
  table: '表',
  fields: [],
  condition: ''
})
const handleEdit = async () => {
  isShowDialog.value = true
  const node = getNode ? getNode() : ''
  if (node) {
    const data = { ...node.getData() }
    console.log(data)
    if (data.datasourceId) {
      formData.datasourceId = data.datasourceId
      dataSourceChange(data.datasourceId)
      formData.tableId = data.tableId
      await tableChange(data.tableId)
      formData.tableReName = data.tableReName
      data.fieldList.forEach((item) => {
        const index = fieldList.value.findIndex((i) => i.COLUMN_NAME == item.COLUMN_NAME)
        fieldList.value[index].tag = item.tag
        fieldList.value[index].reName = item.reName
        tableRef.value.toggleRowSelection(fieldList.value[index], true)
      })
      conditionRef.value.treeData = data.condition
    }
    if (data.datasourceId && data.tableId) {
      tableStatus.value = 'edit'
    }
  }
}
const handleDelete = () => {
  const graph = antvStore.graph
  graph.removeNode(getNode())
}
onMounted(async () => {
  if (prop.type != 'show') {
    console.log(getNode)
    const node = getNode ? getNode() : ''
    const data = { ...node.getData() }
    dataSourceList.value = data.dataSourceList
    if (data.datasourceId) {
      showContent.table = data.tableReName
      showContent.fields = data.fieldList
      showContent.condition = getConditionTreeData(data.condition)
    }
  }
})
const dataSourceChange = (e) => {
  currentDb.value = dataSourceList.value.find((item) => item._id == e)
  findTableName(currentDb.value).then((res) => {
    tableList.value = res.data
  })
}
const tableChange = async (e) => {
  formData.tableReName = e
  await findColumnName({ ...currentDb.value, tableName: e }).then((res) => {
    fieldList.value = res.data.map((item) => {
      return {
        ...item,
        tag: false,
        reName: item.COLUMN_NAME
      }
    })
  })
}
const tableSelect = (e) => {
  console.log(e)
  choosedFields.value = e
}
const handelSubmit = () => {
  if (choosedFields.value.length == 0) {
    ElMessage.warning('请选择字段')
    return
  }
  const node = getNode ? getNode() : ''
  const graph = antvStore.graph
  if (node) {
    console.log(choosedFields.value)
    node.setData(
      {
        ...formData,
        fieldList: choosedFields.value.map((item) => {
          return {
            ...item,
            tableName: formData.tableReName
          }
        }),
        condition: conditionRef.value.treeData
      },
      { deep: false }
    )
    console.log(node)
    showContent.table = formData.tableReName
    showContent.fields = choosedFields.value
    showContent.condition = getConditionTreeData(conditionRef.value.treeData)
    isShowDialog.value = false
    // 判断是否接入end节点
    const edge = graph
      .getEdges()
      .find((item) => item.source.cell == node.id && item.getTargetNode().shape == 'custom-vue-end')
    if (edge) {
      const targetNode = edge.getTargetNode()
      targetNode.setData(
        {
          fields: choosedFields.value.map((item) => {
            return {
              ...item,
              tableName: formData.tableReName,
              joinReName: item.reName
            }
          })
        },
        { deep: false }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.table-box {
  height: 100%;
  width: 100%;
  overflow: auto;
  .table-box-title {
    height: 100%;
    width: 100%;
    background-color: #fff;
    color: #409eff;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 10px;
    border: 3px solid #409eff;
    &:hover {
      color: #fff;
      background-color: #409eff;
    }
  }
}
.box {
  height: 100%;
  width: 100%;
  background-color: #f9f9f9;
  box-shadow: 0 0 10px #ccc;
  border-radius: 10px;
  border: 2px solid #409eff;
  .header {
    padding: 10px;
    border-bottom: 1px solid #409eff;
    color: #409eff;
    font-size: 18px;
    font-weight: 700;
    display: flex;
    align-items: center;
    .title {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .btn {
      margin: 0 5px;
      cursor: pointer;
    }
  }
}
.box-content {
  height: calc(100% - 70px);
  overflow: auto;
  padding: 10px;
  .box-content-item {
    display: flex;
    .label {
      width: 50px;
      text-align: right;
      color: #888;
    }
    .value {
      width: calc(100% - 50px);
    }
  }
  .el-tag {
    margin: 0 5px 5px 0;
  }
}
</style>
